<template>
  <view class="content">
    <view class="modal_phone_bk" v-if="isShowBindPhone" @click="isShowBindPhone = false"> </view>
    <view class="modal_phone" v-if="isShowBindPhone">
      <view class="modal_title">
        <text style="font-size: 32rpx; font-weight: 500">绑定手机号</text>
        <text style="margin-top: 50rpx; color: #747474; font-size: 24rpx">为了更好的为您服务</text>
        <text style="color: #747474; font-size: 24rpx">请绑定手机号</text>

        <view style="color: #747474; font-size: 22rpx; display: flex; align-items: center; margin-top: 20rpx; margin-bottom: 20rpx">
          <u-checkbox checked :name="1" size="12" :customStyle="{ marginBottom: '8px' }" />

          我已阅读并同意
          <text class="blue" @click="openAgreement(0)">《用户协议》</text>
          和
          <text class="blue" @click="openAgreement(1)">《隐私协议》</text>
        </view>
      </view>

      <view class="modal_option">
        <view class="r_btn">
          <button
            type="default"
            class="use_btn"
            :style="{
              backgroundColor: titleBg,
              color: titleTextBg,
            }"
            @click="cancel"
          >
            取消
          </button>
        </view>
        <view class="r_btn">
          <button
            class="use_btn"
            :style="{
              backgroundColor: titleBg,
              color: titleTextBg,
            }"
            open-type="getPhoneNumber"
            @getphonenumber="getPhoneNumber"
          >
            绑定手机号
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { nextTick, onBeforeMount, onMounted, reactive, ref, watch } from "vue";
import { getOrderData, doAuth, doWxAuth, getSiteAgreement } from "@/utils/api";

const props = defineProps({
  jsonPage: {
    type: Object,
    default: () => {},
  },
});

const userInfo = ref({});
const codeWx = ref();
const isShowBindPhone = ref(false);
const titleBg = ref();
const titleTextBg = ref();
const agreementCheck = ref(1);

onBeforeMount(() => {
  titleBg.value = uni.getStorageSync("backgroundColor");
  titleTextBg.value = uni.getStorageSync("color");

  nextTick(() => {
    setTimeout(() => {
      if (uni.getSystemInfoSync().uniPlatform == "mp-alipay") {
        // 支付宝
        my.getOpenUserInfo({
          success: (res) => {
            let resObj = JSON.parse(res.response);
            Object.assign(userInfo, {
              ...resObj.response,
            });

            my.getAuthCode({
              scopes: ["auth_base"],
              success: (res) => {
                const authCode = res.authCode;

                doAuthFn(authCode, resObj);
              },
              fail: (err) => {
                console.log("my.getAuthCode 调用失败", err);
              },
            });
          },
          fail: (err) => {
            console.log("my.getAuthCode 调用失败", err);
          },
        });
      } else {
        // 微信
        if (!uni.getStorageSync("openId")) {
          isShowBindPhone.value = true;
        }
      }
    }, 500);
  });
});

function getPhoneNumber(phoneObj) {
  getWxCode(phoneObj.detail);
}

function getWxCode(phoneObj) {
  uni.login({
    success: (res) => {
      if (res.code) {
        //微信登录成功 已拿到code
        codeWx.value = res.code;

        // 获取用户信息
        uni.getUserInfo({
          provider: "weixin",
          success: (infoRes) => {
            console.log("🚀 ~ getWxCode ~ infoRes:", infoRes);
            doWxAuthFn(infoRes.userInfo, phoneObj);
          },
        });
      } else {
        console.log("登录失败！" + res.errMsg);
      }
    },
  });
}
// 团长的id
const teamId = ref();
const emit = defineEmits(["authSuccess", "cancel"]);

/**
 * 微信授权
 * @param userInfo
 */
async function doWxAuthFn(userInfo, phoneObj) {
  let { code, data } = await doWxAuth({
    user_info: JSON.stringify(userInfo),
    js_code: codeWx.value,
    encrypted_data: phoneObj.encryptedData,
    siv: phoneObj.iv,
    teamId: teamId.value,
  });
  if (code == 200) {
    uni.setStorageSync("openId", data.openId);
    isShowBindPhone.value = false;
    emit("authSuccess", userInfo.value);
  }
}

/**
 * 支付宝授权
 * @param authCode
 * @param resObj
 */
async function doAuthFn(authCode, resObj) {
  let { code, data } = await doAuth({
    code: authCode,
    avatar: resObj.response.avatar,
    nickName: resObj.response.nickName,
  });
  if (code == 200) {
    uni.setStorageSync("openId", data.openId);
    emit("authSuccess", userInfo.value);
  }
}

// 授权成功回调
function onGetAuthorize() {
  my.getOpenUserInfo({
    fail: (res) => {
      console.log(res);
    },
    success: (res) => {
      const userInfo = JSON.parse(res.response).response; // 以下方的报文格式解析两层 response
      my.alert({
        content: userInfo,
      });
    },
  });
}

// 授权失败回调
function onAuthError() {
  uni.showToast({
    title: "授权失败回调",
  });
}

async function openAgreement(type) {
  let { code, data } = await getSiteAgreement();

  uni.navigateTo({
    url: "/pages/htmlView/index?html=" + encodeURIComponent(data[type]),
  });
}

function cancel() {
  isShowBindPhone.value = false;
  emit("cancel");
}
</script>

<style lang="scss" scoped>
.modal_phone_bk {
  position: fixed;
  top: 0;
  width: 100vw;
  height: 100vh;
  background-color: rgb(0, 0, 0, 0.5);
  z-index: 9999;
}

.modal_phone {
  position: fixed;
  top: 400rpx;
  left: 100rpx;
  width: 600rpx;
  // height: 250rpx;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  justify-content: space-between;
  padding-top: 50rpx;
  padding-bottom: 30rpx;
  border-radius: 10rpx;
  z-index: 99999;
}

.modal_option {
  width: 100%;
  display: flex;
  flex-direction: row;
}

.use_btn {
  width: 70%;
  height: 50rpx;
  line-height: 50rpx;
  font-size: 24rpx;
  border-radius: 100rpx;
  background-color: #8ec3ac;
}

.r_btn {
  width: 50%;
  display: flex;
  text-align: center;
  justify-content: center;
  align-items: center;
}

.modal_title {
  display: flex;
  flex-direction: column;
}

.blue {
  color: #4554ff;
}
</style>
